#pragma once

#include <spdlog/spdlog.h>
#include <filesystem>
#include <chrono>
#include <string>

class LogManager {
public:
    LogManager();
    ~LogManager();

    // 初始化日志系统
    void initialize();
    
    // 归档和清理日志
    void archiveAndClean();

    // 配置
    void setRetentionDays(int days) { retention_days_ = days; }
    void setMaxLogSize(size_t size) { max_log_size_ = size; }
    void setMaxLogFiles(size_t count) { max_log_files_ = count; }

    // 健康检查
    bool healthCheck() const;
    
    // 获取磁盘使用情况
    double getDiskUsage() const;
    
    // 性能统计
    struct PerformanceStats {
        size_t filesCompressed = 0;
        size_t bytesSaved = 0;
        double compressionRatio = 0.0;
        std::chrono::milliseconds lastOperationTime{0};
    };
    PerformanceStats getStats() const { return stats_; }

    // 日志轮转策略
    enum class RotationStrategy {
        SIZE,       // 基于大小
        HOURLY,     // 每小时
        DAILY       // 每天
    };
    void setRotationStrategy(RotationStrategy strategy) { rotation_strategy_ = strategy; }

    // 远程日志配置
    void enableRemoteLogging(const std::string& host, int port);
    void disableRemoteLogging();

    // 日志过滤
    void addFilter(const std::string& pattern, bool is_regex = false);
    void clearFilters();

    // 异步日志控制
    void setAsyncMode(bool enabled, size_t queue_size = 8192, size_t flush_interval_ms = 1000);
    
    // 日志采样
    void setSamplingRate(double rate) { sampling_rate_ = rate; }
    
    // 动态日志级别
    void setLogLevel(const std::string& logger_name, spdlog::level::level_enum level);
    void setGlobalLogLevel(spdlog::level::level_enum level);

    // 资源监控
    struct ResourceUsage {
        size_t queue_size;
        size_t memory_usage;
        double cpu_usage;
    };
    ResourceUsage getResourceUsage() const;

private:
    void setupLoggers();
    bool compressFile(const std::filesystem::path& path);
    void cleanOldLogs();
    bool checkDiskSpace() const;
    void rotateByTime();
    void setupRemoteSink();
    void monitorResources();
    bool shouldSample() const;

    // 异步日志队列
    std::shared_ptr<spdlog::details::thread_pool> async_pool_;
    size_t async_queue_size_ = 0;
    
    // 采样率 (0.0 - 1.0)
    double sampling_rate_ = 1.0;
    
    // 资源监控
    std::atomic<size_t> current_queue_size_{0};
    std::thread monitor_thread_;
    std::atomic<bool> monitor_running_{false};

    RotationStrategy rotation_strategy_ = RotationStrategy::SIZE;
    std::vector<std::pair<std::regex, bool>> filters_;
    std::shared_ptr<spdlog::sinks::syslog_sink> syslog_sink_;
    
    // 成员变量
    int retention_days_ = 30;
    size_t max_log_size_ = 10 * 1024 * 1024; // 10MB
    size_t max_log_files_ = 5;
    std::chrono::system_clock::time_point last_archive_time_;
    
    // 性能统计
    PerformanceStats stats_;
};